package com.hdu.hot100.list;

public class lc25 {


    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    class Solution {
        public ListNode reverseKGroup(ListNode head, int k)
        {

            ListNode dummy = new ListNode(0);
            dummy.next = head;

            ListNode prev = dummy;
            ListNode end = dummy;

            while (end != null)
            {
                for (int i = 0; i < k && end != null; i++)
                {
                    end = end.next;
                }
                if (end == null)
                {
                    break;
                }

                ListNode start = prev.next;
                ListNode next = end.next;

                prev.next = null;
                end.next = null;

                ListNode newNode = reverseList(start);

                prev.next = newNode;
                start.next = next;

                prev = start;
                end = start;
            }

            return dummy.next;
        }

        ListNode reverseList(ListNode head)
        {
            if (head == null || head.next == null)
            {
                return head;
            }
            ListNode p = reverseList(head.next);
            head.next.next = head;
            head.next = null;
            return p;
        }
    }
}
